package com.kgc.server.service.impl;

import com.kgc.server.dao.BuyCarDao;
import com.kgc.server.dao.ProductDao;
import com.kgc.server.pojo.EasybuyCar;
import com.kgc.server.pojo.Collection;
import com.kgc.server.pojo.EasybuyProduct;
import com.kgc.server.pojo.Page;
import com.kgc.server.service.ProductService;
import com.kgc.server.util.ResponseMessage;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.common.SolrDocumentList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ProductServiceImpl implements ProductService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ProductDao productDao;
    @Autowired
    private SolrClient solrClient;
    @Autowired
    private BuyCarDao buyCarDao;

    @Override
    public ResponseMessage addProductToSole() {
        logger.info("ProductServiceImpl addProductToSole start...");
        ResponseMessage msg = new ResponseMessage();
        List<EasybuyProduct> allProduct = productDao.getAllProduct();
        try {
            UpdateResponse updateResponse = solrClient.addBeans(allProduct);
            logger.info("ProductServiceImpl addProductToSole allProduct:" + allProduct + ";updateResponse:" + updateResponse);
            if (updateResponse.getStatus() == 0) {
                solrClient.commit();
                msg.setMsg("添加成功");
                msg.setCode("200");
                msg.setData(allProduct);
            }else {
                solrClient.rollback();
                msg.setMsg("添加失败");
                msg.setCode("500");
            }
        } catch (Exception e) {

            msg.setMsg("添加失败");
            msg.setCode("500");
            logger.error("ProductServiceImpl addProductToSole error...",e);

            e.printStackTrace();
        }
        return msg;
    }

    @Override
    public ResponseMessage addProduct(EasybuyProduct easybuyProduct) {
        logger.info("ProductServiceImpl addProduct params: easybuyProduct"+easybuyProduct);
        ResponseMessage responseMessage = new ResponseMessage();
        Integer integer = productDao.addProduct(easybuyProduct);
        responseMessage.setData(integer);
        responseMessage.setMsg("添加成功！");
        responseMessage.setCode("200");

        return responseMessage;
    }

    @Override
    public ResponseMessage getAllProduct() {
        ResponseMessage msg = new ResponseMessage();
        List<EasybuyProduct> allProduct = productDao.getAllProduct();
        msg.setCode("200");
        msg.setData(allProduct);
        return msg;
    }

    @Override
    public ResponseMessage getProductById(String productId) {
        logger.info("ProductServiceImpl showProductById start param:"+productId);
        ResponseMessage responseMessage = new ResponseMessage();
        try{
            SolrQuery query = new SolrQuery();
            query.setQuery("id:"+productId);
            QueryResponse qr = solrClient.query(query);
            List<EasybuyProduct> productList = qr.getBeans(EasybuyProduct.class);
            responseMessage.setData(productList);
            responseMessage.setCode("200");
        }catch (Exception e){
            logger.error("ProductServiceImpl showProductById iserror",e);
            responseMessage.setMsg("出错了");
            responseMessage.setCode("500");
        }
        return responseMessage;

    }

    /* @Override
     public int updataProductListById(EasybuyProduct product){
         int num = productDao.updataProductListById(product);
         return num;
     }*/
    @Override
    public int delProductListById(int id) {
        return productDao.delProductListById(id);
    }

    @Override
    public List getProductListById(int id) {

        return productDao.getProductListById(id);
    }

    @Override
    public int updataProductListById(EasybuyProduct product) {
        int num = productDao.updataProductListById(product);
        return num;
    }

    @Override
    public ResponseMessage getProductForSolr(Integer categoryLevel1Id, Integer categoryLevel3Id, String name, Integer pageNo) {
        logger.info("ProductServiceImpl getProductForSolr params : getCategoryLevel1Id:" + categoryLevel1Id + ";getCategoryLevel3Id :" + categoryLevel3Id + ";name:" + name + ";pageNo:" + pageNo);
        ResponseMessage msg = new ResponseMessage();
        SolrQuery solrQuery = new SolrQuery();
        if (categoryLevel1Id != null && !"".equals(categoryLevel1Id)) {
            solrQuery.setQuery("categoryLevel1Id_i:" + categoryLevel1Id);
            /*if (name != null && !"".equals(name)) {
                solrQuery.setFilterQueries("name_ik:" + name);
            }*/
        } else {
            if (categoryLevel3Id != null && !"".equals(categoryLevel3Id)) {
                solrQuery.setQuery("categoryLevel3Id_i:" + categoryLevel3Id);
            } else {
                if (name != null && !"".equals(name)) {
                    solrQuery.setQuery("name_ik:" + name);
                }else {
                    solrQuery.setQuery("*:*");
                }
            }
        }
        Page page = new Page();
        Integer pageSize = 4;
        page.setPageSize(pageSize);
        page.setPageNo(pageNo);
        solrQuery.setStart((pageNo - 1) * pageSize);
        solrQuery.setRows(pageSize);
        solrQuery.addHighlightField("name_ik");
        solrQuery.setHighlight(true);
        solrQuery.setHighlightSimplePre("<font color='red'>");
        solrQuery.setHighlightSimplePost("</font>");
        try {
            QueryResponse response = solrClient.query(solrQuery);
            Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();
            SolrDocumentList results = response.getResults();
            page.setCount((int) results.getNumFound());

            List<EasybuyProduct> productsList = new ArrayList<EasybuyProduct>();
            List<EasybuyProduct> easybuyProductList = response.getBeans(EasybuyProduct.class);
            page.setList(easybuyProductList);
            logger.info("ProductServiceImpl getProductForSolr params : getCategoryLevel1Id:" + categoryLevel1Id + ";getCategoryLevel3Id :" + categoryLevel3Id + ";name:" + name + ";pageNo:" + pageNo + ";result:" + easybuyProductList);
            System.out.println(results.getNumFound());
            for (EasybuyProduct easybuyProduct : easybuyProductList) {
                if (highlighting.containsKey(easybuyProduct.getId())) {
                    Map<String, List<String>> stringListMap = highlighting.get(easybuyProduct.getId());
                    for (Map.Entry<String, List<String>> entry : stringListMap.entrySet()) {
                        if("name_ik".equals(entry.getKey())){
                            String s = entry.getValue().get(0);
                            easybuyProduct.setName(s);
                            productsList.add(easybuyProduct);

                        }
                    }

                }
            }
            msg.setCode("200");
            if(productsList.size()>0){
                page.setList(productsList);
            }
            msg.setData(page);
            msg.setMsg("查询成功！");
        } catch (Exception e) {
            msg.setMsg("查询错误！");
            msg.setCode("500");
            e.printStackTrace();
        }
        return msg;
    }

    @Override
    public List getProductList(Page page){
        //设置总数
        int num = productDao.getCount();
        page.setCount(num);
        if( page.getCount() % page.getPageSize() == 0 ){
            page.setPageCount(page.getCount() / page.getPageSize());
        }else{
            page.setPageCount(page.getCount() / page.getPageSize() + 1);
        }
        page.setNum((page.getPageNo()-1)*page.getPageSize());
        return productDao.getProductList(page);
    }
    @Override
    public boolean setGoodsCollection(int goodsID, int UserID) {
        boolean flag = productDao.setGoodsCollection(goodsID,UserID);
        return flag;
    }

    @Override
    public boolean delGoodsCollection(int goodsID,int userID) {
        boolean flag = productDao.delGoodsCollection(goodsID,userID);
        return flag;
    }

    @Override
    public ResponseMessage stockIsEnough(String userId) {
        logger.info("ProductServiceImpl stockIsEnough param userId:"+userId);
        ResponseMessage msg = new ResponseMessage();
        //获取用户的购物车
        List<EasybuyCar> easybuyCars = buyCarDao.selectUserCar(userId);
        logger.info("ProductServiceImpl stockIsEnough param userId:"+userId+";easybuyCars:"+easybuyCars);
        //循环判断购物车里的商品够不够
        for(EasybuyCar easybuyCar:easybuyCars){
            EasybuyProduct productById = productDao.getProductById(easybuyCar.getProductId());
            logger.info("ProductServiceImpl stockIsEnough param userId:"+userId+";easybuyCars:"+easybuyCars+";productById:"+productById);
            //如商品库存不够就返回商品信息
            if(productById.getStock()<easybuyCar.getProductNum()){
                msg.setMsg("库存不够！");
                msg.setCode("400");
                msg.setData(productById);
                return msg;
            }
        }
        msg.setData(null);
        msg.setCode("200");
        msg.setMsg("库存足够");
        return msg;
    }

   /* @Override
    public ResponseMessage productStock(Integer productId, Integer productNum) {
        logger.info("ProductServiceImpl productStock params: productId:"+productId+";productNum:"+productNum);
        ResponseMessage msg = new ResponseMessage();
        EasybuyProduct productById = productDao.getProductById(productId.toString());
        Integer stock = productById.getStock()-productNum;
        if(stock>0){
            int i = productDao.modifyProductStock(productId, stock);
            msg.setCode("200");
            msg.setMsg("扣除库存成功！");
            msg.setData(i);
        }else {

        }
        return null;
    }*/

    @Override
    public boolean getCollection(int goodsID, int userID){
        List list = productDao.getCollection(goodsID,userID);
        if( list.size() != 0 ){
            return true;
        }
        return false;
    }


    @Override
    public List getUserProductListByUserId(int userID){
        List list = productDao.getUserProductListByUserId(userID);
        return list;
    }

    @Override
    public List getCollectionFy(Page page,int userID) {
        //设置总数
        int num = productDao.getCollectionCount(userID);

        page.setCount(num);

        page.setUserID(userID);

        if( page.getCount() % page.getPageSize() == 0 ){
            page.setPageCount(page.getCount() / page.getPageSize());
        }else{
            page.setPageCount(page.getCount() / page.getPageSize() + 1);
        }

        page.setNum((page.getPageNo()-1)*page.getPageSize());

        List list = productDao.getCollectionFy(page);

        return list;
    }

    @Override
    public int delCollectionByUserIdORID(int userID, int goodsID) {
        int num = productDao.delCollectionByUserIdORID(userID,goodsID);
        return num;
    }

    @Override
    public List getCollectionAll(int userID){
        List list = productDao.getCollectionAll(userID);
        return list;
    }
}
